<template>
  <el-dialog
      v-model="visible"
      :title="title"
      :close-on-click-modal="false"
      destroy-on-close
  >
    <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="importApi"
        :headers="headers"
        :data="extraData"
        :auto-upload="false"
        :file-list="fileList"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :accept="acceptTypes"
        drag
    >
      <el-icon class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          {{ tipText }}
        </div>
      </template>
    </el-upload>

    <!-- 导入模板下载 -->
    <div class="mt-4 p-3 bg-gray-50 rounded" v-if="templateApi">
      <div class="flex items-center justify-between">
        <span class="text-sm text-gray-600">下载导入模板</span>
        <el-button type="text" @click="handleDownloadTemplate" size="small">
          <i class="el-icon-download mr-1"></i>下载模板
        </el-button>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button
          type="primary"
          :loading="loading"
          :disabled="fileList.length === 0"
          @click="handleConfirm"
      >
        {{ confirmText }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {UploadFilled} from '@element-plus/icons-vue'
import {downloadFileV2, uploadFileV2} from "@/utils/download.js";

const props = defineProps({
  modelValue: {type: Boolean, default: false},
  title: {type: String, default: '导入数据'},
  acceptTypes: {type: String, default: '.xlsx, .xls, .csv'},
  maxSize: {type: Number, default: 10},
  tipText: {type: String, default: '支持 .xlsx, .xls, .csv 格式文件'},
  confirmText: {type: String, default: '开始导入'},
  // 导入接口地址
  importApi: {type: String, default: ''},
  // 模板下载接口地址
  templateApi: {type: String, default: ''},
  // 请求头
  headers: {type: Object, default: () => ({})},
  // 额外参数
  extraData: {type: Object, default: () => ({})},
  // 自定义导入处理函数（优先级高于 importApi）
  onImport: {type: Function, default: null},
  // 自定义模板下载处理函数（优先级高于 templateApi）
  onDownloadTemplate: {type: Function, default: null}
})

const emit = defineEmits(['update:modelValue', 'success', 'error', 'cancel'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const loading = ref(false)
const fileList = ref([])
const uploadRef = ref()

const handleFileChange = (file) => {
  const isValidType = props.acceptTypes.split(",").some(type =>
      file.name.toLowerCase().endsWith(type.replace('.', ''))
  )
  if (!isValidType) {
    ElMessage.error(`只能上传 ${props.acceptTypes} 格式文件!`)
    fileList.value = fileList.value.filter(item => item.uid !== file.uid)
    return false
  }

  const isLtMaxSize = file.size / 1024 / 1024 < props.maxSize
  if (!isLtMaxSize) {
    ElMessage.error(`文件大小不能超过 ${props.maxSize}MB!`)
    fileList.value = fileList.value.filter(item => item.uid !== file.uid)
    return false
  }

  fileList.value = [file]
}

const handleFileRemove = () => {
  fileList.value = []
}

const handleDownloadTemplate = async () => {
  try {
    if (props.onDownloadTemplate) {
      // 使用自定义处理函数
      await props.onDownloadTemplate()
    } else if (props.templateApi) {
      // 使用接口地址下载
      await downloadTemplateByUrl()
    } else {
      ElMessage.warning('模板下载功能未配置')
      return
    }
    ElMessage.success('模板下载成功')
  } catch (error) {
    ElMessage.error('模板下载失败: ' + (error.message || '未知错误'))
  }
}
const downloadTemplateByUrl = async () => {
  await downloadFileV2({}, props.templateApi, '导入模板.xlsx')
}

const handleConfirm = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要导入的文件')
    return
  }

  try {
    loading.value = true

    if (props.onImport) {
      await props.onImport(fileList.value[0].raw)
    } else if (props.importApi) {
      if (!fileList.value.length) {
        throw new Error('请先选择文件')
      }
      const formData = new FormData();
      formData.append('file', fileList.value[0].raw);

      await uploadFileV2(formData, props.importApi)
    } else {
      throw new Error('导入功能未配置')
    }

    ElMessage.success('导入成功')
    visible.value = false
    fileList.value = []
    emit('success')
  } catch (error) {
    ElMessage.error('导入失败: ' + (error.message || '未知错误'))
    emit('error', error)
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  visible.value = false
  fileList.value = []
  emit('cancel')
}

</script>